import React, { PureComponent, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, DatePicker, Badge, Divider } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './DevFix.less';
import OperationForm from '../../components/OperationForm';
import FullCalendar from '@fullcalendar/react';
import timeGridPlugin from '@fullcalendar/timegrid';
import interactionPlugin from '@fullcalendar/interaction';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
// const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['待处理', '处理中', '已处理'];
const statusMap = ['default', 'processing', 'success', 'error'];
const bindstatus = ['未绑定', '已绑定'];

@connect(({ devfix }) => ({
  devfix,
}))
@Form.create()
export default class DevFix extends PureComponent {
  state = {
    selectedRows: [],
    record: {},
    modalVisible: false,
    opType: 'devbind',
  };

  componentDidMount() {
    const payload = {};
    const { dispatch } = this.props;
    dispatch({
      type: 'devfix/fetch',
      payload,
    });
  }

  onbind = record => {
    this.setState({ record });
    this.handleModalVisible(true, this.state.opType);
  };
  handleModalVisible = (flag, opType) => {
    // console.log('modal visible', flag, opType);
    this.setState({
      modalVisible: !!flag,
      opType,
    });
  };

  getFromValue = () => {
    const { form } = this.props;
    let postvalue = {};
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { entries } = Object;

      for (const [key, value] of entries(fieldsValue)) {
        if (value !== null && value !== undefined) {
          postvalue[key] = value;
        }
      }
      //console.log('postvalue', postvalue);
      if (postvalue.date && postvalue.date.length > 0) {
        const startSubDate = postvalue.date[0].format('YYYY-MM-DD');
        const endSubDate = postvalue.date[1].format('YYYY-MM-DD');
        postvalue = {
          ...postvalue,
          startSubDate,
          endSubDate,
        };
        delete postvalue.date;
      }
    });
    return postvalue;
  };
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    const postvalue = this.getFromValue();
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...postvalue,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'devfix/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'devfix/fetch',
      payload: {},
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const postvalue = this.getFromValue();
    dispatch({
      type: 'devfix/fetch',
      payload: postvalue,
    });
  };

  downloadFile = () => {
    //  const fileName = '';

    const postvalue = this.getFromValue();
    this.props.dispatch({
      // 发送请求
      type: 'devfix/export',
      payload: postvalue,
      callback: response => {
        const aLink = document.createElement('a'); // 创建a链接
        aLink.style.display = 'none';
        aLink.href = response;
        //    aLink.download = fileName;
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink); // 点击完成后记得删除创建的链接
      },
    });
  };
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem>
              {getFieldDecorator('date')(
                <RangePicker
                  format="YYYY-MM-DD"
                  placeholder={['开始日期', '结束日期']}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={3} sm={24}>
            <FormItem>
              {getFieldDecorator('devUuid', {
                rules: [{ required: false, message: '请输入设备ID!' }],
              })(<Input placeholder="设备ID" />)}
            </FormItem>
          </Col>
          <Col md={3} sm={24}>
            <FormItem>
              {getFieldDecorator('vehLicplateNo', {
                rules: [{ required: false, message: '请输入车牌号!' }],
              })(<Input placeholder="车牌号" />)}
            </FormItem>
          </Col>

          <Col md={3} sm={24}>
            <FormItem>
              {getFieldDecorator('reportor', {
                rules: [{ required: false, message: '请输入报修人!' }],
              })(<Input placeholder="报修人" />)}
            </FormItem>
          </Col>
          <Col md={3} sm={24}>
            <FormItem>
              {getFieldDecorator('orgName', {
                rules: [{ required: false, message: '请输入单位名称!' }],
              })(<Input placeholder="单位名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <Button type="primary" htmlType="submit" style={{ marginRight: 10 }}>
              查询
            </Button>

            <Button type="primary" style={{ marginRight: 10 }} onClick={() => this.downloadFile()}>
              导出
            </Button>
            <Button
              type="primary"
              style={{ marginRight: 10 }}
              onClick={() => {
                this.props.history.push(`/devmaintain/devreport`);
              }}
            >
              我要报修
            </Button>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    // //console.log('task', this.props.task);
    const { devfix, loading } = this.props;
    const { selectedRows } = this.state;
    const columns = [
      {
        title: '提交日期',
        dataIndex: 'subDate',
      },
      {
        title: '设备ID',
        dataIndex: 'devUuid',
      },

      {
        title: '车牌号',
        dataIndex: 'vehLicplateNo',
      },
      {
        title: '报修人',
        dataIndex: 'reportor',
      },
      {
        title: '报修单位',
        dataIndex: 'orgName',
      },
      {
        title: '问题描述',
        dataIndex: 'faultDescr',
      },
      {
        title: '处理状态',
        dataIndex: 'procStatus',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '绑定状态',
        dataIndex: 'bindFlag',
        render(val) {
          return <Badge status={statusMap[val]} text={bindstatus[val]} />;
        },
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <Link
              to={{
                pathname: `/devmaintain/repairDet/${record.repairId}`,
                record,
              }}
            >
              详情
            </Link>
            <Divider type="vertical" />
            {record.bindFlag ? <a onClick={() => this.onbind(record)}>解绑</a> : null}
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="任务查询">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <StandardTable
              rowKey="setId"
              selectedRows={selectedRows}
              loading={loading}
              data={devfix}
              columns={columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <OperationForm
          handleModalVisible={this.handleModalVisible}
          modalVisible={this.state.modalVisible}
          dispatch={this.props.dispatch}
          opType={this.state.opType}
          record={this.state.record}
        />
      </PageHeaderLayout>
    );
  }
}
